package com.iamback.dy.task.taskjob;

import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.HashSet;
import java.util.List;
import java.util.Map;

import org.apache.logging.log4j.LogManager;
import org.apache.logging.log4j.Logger;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import com.alibaba.fastjson.JSON;
import com.aliyuncs.exceptions.ClientException;
import com.iamback.dy.config.redis.RedisTemplateUtil;
import com.iamback.dy.entity.ContentUnreviewed;
import com.iamback.dy.mapper.ContentUnreviewedMapper;
import com.iamback.dy.task.common.httpConfg.HttpAPIService;
 
/**
 * 阿里云 对文本 图片 视频检测
 * @author LJ
 */
@Component
public class AlyunTestingTask {
	 private static Logger ILOG = LogManager.getLogger(AlyunTestingTask.class);
	@Autowired
	private ContentUnreviewedMapper contentUnreviewedMapper;
	@Autowired
	private AliAuditAdapter aliAuditAdapter;
	@Autowired
	private RedisTemplateUtil redisTemplateUtil;
	@Autowired
	private HttpAPIService httpAPIService;
	

	@Value("${DY.EX.HTTPURL}")
	private String httpUrl;
	
	@Value("${DY.EX.TOKEN}")
	private String token;
	
	
    private volatile int last_id = Integer.MAX_VALUE;
    private volatile int runtimes = 0;
    private HashSet<String>  idSet = new HashSet<String>();

    @Scheduled(fixedRate = 60000)
	public void taskAlyun(){
    	try {
    		taskAudit();
			fetchVideoAliResult();
		} catch (UnsupportedEncodingException | ClientException e) {
			e.printStackTrace();
		} 
	}
    
    
	/**
	 * 从数据库中检测需要检测的帖子
	 * @throws ClientException 
	 * @throws UnsupportedEncodingException 
	 */
	public void taskAudit() throws UnsupportedEncodingException, ClientException{
		List<ContentUnreviewed> contentUnrevieweds=contentUnreviewedMapper.getContentUnreviewedByTask(Long.valueOf(last_id));
		int count = 0;
		for(ContentUnreviewed contentUnreviewed:contentUnrevieweds){
 			 if(contentUnreviewed.getContentType().equals("2")) {
	              auditText(String.valueOf(contentUnreviewed.getDyContentId()), contentUnreviewed.getContentText());
	         } else if (contentUnreviewed.getContentType().equals("3")) {
	              auditImage(String.valueOf(contentUnreviewed.getDyContentId()), contentUnreviewed.getContentText(), contentUnreviewed.getContentUrl());
	         } else if (contentUnreviewed.getContentType().equals("4")) {
	              submitVideo(String.valueOf(contentUnreviewed.getDyContentId()), contentUnreviewed.getContentText(), contentUnreviewed.getContentUrl(),contentUnreviewed.getDuration());
	         }
			count++;
			last_id = Math.min(last_id,  contentUnreviewed.getDyContentId().intValue());
	    }
	    runtimes++;
	  //一次走200个，走3次，10分钟再从头来一次
        if (count < 100 || runtimes >= 3) {
            last_id = Integer.MAX_VALUE;
            runtimes =0 ;
        }
	}
	
	
	/**
	 * 视频结果获取
	 */
	public void fetchVideoAliResult() {
		try {
			while (true) {
				HashMap<String, Integer> result = aliAuditAdapter.getResult();
				ILOG.info("check vedio by ali result is:" + result);
				if (result == null || result.size() == 0) {
					return;
				}
				for (String contentId : result.keySet()) {
					this.idSet.remove(contentId);
					int code = result.get(contentId);
					if (0 == code) {
						auditPass(contentId);
						ILOG.info("alAuth result:pass " + contentId);
					} 
					else if (1 == code){
						auditFail(contentId, "5");
						ILOG.warn("alAuth result:content machine audit video fail, dyContentId: {}", contentId);
					}
					else if (2 == code){
						auditFail(contentId, "4");
						ILOG.warn("alAuth result:content machine audit video fail, dyContentId: {}", contentId);
					}
					else {
						auditFail(contentId, "F");
						ILOG.warn("alAuth result:content machine audit video fail, dyContentId: {}", contentId);
					}
				}
			}
		} catch (UnsupportedEncodingException e) {
			// TODO Auto-generated catch block
			ILOG.error("AliAuditAdapter.inc().submitVideo(aliCheckMap);", e);
		} catch (ClientException e) {
			// TODO Auto-generated catch block
			ILOG.error("AliAuditAdapter.inc().submitVideo(aliCheckMap);", e);
		}
	}
	
	
	
	/**
	 * 帖子文本内容
	 * @param dyContentId
	 * @param contentText
	 * @return
	 * @throws UnsupportedEncodingException
	 * @throws ClientException
	 */
	public int auditText(String dyContentId, String contentText) throws UnsupportedEncodingException, ClientException {
        //int ret = getAuditTextRet(dyContentId, contentText);
    	int ret = aliAuditAdapter.auditText(contentText, dyContentId);
        if(ret == 0) {
        	auditPassOnline(dyContentId);
            ILOG.info("content machine audit text pass, id: {}, content: {}, image: {}, video: {}",
                    dyContentId, contentText, "", "");
        } else if(ret == 1) {
            auditFail(dyContentId, "5"); // 机器存疑, 人工再审
            ILOG.info("content machine audit text not pass 1, id: {}, content: {}, image: {}, video: {}",
                    dyContentId, contentText, "", "");
        } else if(ret == 2) {
            auditFail(dyContentId, "4"); // 机器不通过, 直接不通过, 量不大
            ILOG.info("content machine audit text fail 2, id: {}, content: {}, image: {}, video: {}",
                    dyContentId, contentText, "", "");
        }
        else {
        	auditFail(dyContentId, "F"); // 机器不通过, 直接不通过, 量不大
            ILOG.info("content machine audit text fail, id: {}, content: {}, image: {}, video: {},ret:{}",
                    dyContentId, contentText, "", "",ret);
        }
        return ret;
    }
	
	
	/**
	 * 帖子 图片检测
	 * @param dyContentId
	 * @param contentText
	 * @param imageUrl
	 * @return
	 * @throws UnsupportedEncodingException
	 * @throws ClientException
	 */
	public int auditImage(String dyContentId, String contentText, String imageUrl) throws UnsupportedEncodingException, ClientException {
		ILOG.info("begin audit image {}!",dyContentId);
		
		int ret = 0;
		if (contentText!= null && !"".equals(contentText.trim())){
			ret = aliAuditAdapter.auditText(contentText, dyContentId);
			ILOG.info("begin audit image's text id:{},ret{}!",dyContentId,ret);
		}else{
			ILOG.info("begin audit image's text id:{},text is null pass!",dyContentId);
		}
		
		if (ret == 0) {
			if (imageUrl==null||imageUrl.trim().equals("")) {
				auditFail(dyContentId,"8");
				ILOG.info("content machine audit image pass, id: {}, content: {}, image: {}, video: {}", dyContentId,
						contentText, imageUrl, "");
				return 1; 
            } else {

				int imageRet = aliAuditAdapter.auditImage(imageUrl,dyContentId);
				if (imageRet == 0) {
					auditPass(dyContentId); // 通过
					ILOG.info("alAuth result:img-content machine audit image pass, id: {} ",
							dyContentId);

				} else if (imageRet == 1) {
					auditFail(dyContentId, "5"); // 转人工
					ILOG.info("alAuth result:img-content machine audit image not pass, id: {}, content: {}, image: {}, video: {}",
							dyContentId, contentText, imageUrl, "");

				} else if (imageRet == 2) {
					auditFail(dyContentId, "4"); // 直接拒掉
					ILOG.info("alAuth result:img-content machine audit image fail, id: {}, content: {}, image: {}, video: {}",
							dyContentId, contentText, imageUrl, "");

				} else {
					auditFail(dyContentId, "F"); // 送阿里云错误
					ILOG.info("alAuth result:img-content machine audit image unknown, id: {}, content: {}, image: {}, video: {}, ret: {}",
							dyContentId, contentText, imageUrl, "", ret);
				}
		

            } 
        } else if(ret == 1) {
            auditFail(dyContentId, "5");  // 转人工
            ILOG.info("content machine audit text of image not pass, id: {}, content: {}, image: {}, video: {}",
                    dyContentId, contentText, imageUrl, "");

        } else if(ret == 2){
            auditFail(dyContentId, "4"); // 机器审核不通过
            ILOG.info("content machine audit text of image fail, id: {}, content: {}, image: {}, video: {}",
                    dyContentId, contentText, imageUrl, "");
        }
        else{
        	auditFail(dyContentId, "F"); // 机器审核不通过
        	ILOG.info("content machine audit text of image fail, id: {}, content: {}, image: {}, video: {},ret : {}",
                    dyContentId, contentText, imageUrl, "",ret);
        }

        return ret;
    }
	
	/**
	 * 视频 video 检测
	 * @param dyContentId
	 * @param contentText
	 * @param videoUrl
	 * @param duration
	 * @return
	 */
	public int submitVideo(String dyContentId, String contentText, String videoUrl,String duration) { 
    	int ret = 0;
    	try{
    		if (this.idSet.contains(dyContentId)){
    			ILOG.info("content alread  Exist: {}",dyContentId);
    			return 0;
    		}
    		ret = 0;
    		if (contentText != null && !"".equals(contentText.trim())){
    			ret = aliAuditAdapter.auditText(contentText, dyContentId);
    	        ILOG.info("content machine audit video's url fail id:{},ret:{}", dyContentId, ret);
    		}
    		else{
    			ILOG.info("content machine audit video's text id:{},text is null", dyContentId);
    		}
	        
	        if(ret == 0) {
	            if (videoUrl!=null&&!"".equals(videoUrl)) {
	            	int videoRet = aliAuditAdapter.submitVideo(videoUrl, dyContentId);
	                ILOG.info("content machine audit submit complete, id: {}, content: {}, image: {}, video: {}, ret: {}", dyContentId, contentText, "", videoUrl, videoRet);
	                this.idSet.add(dyContentId);
	            }else{
	            	auditFail(dyContentId, "F"); // 机器审核不通过
	            }
	        } else if(ret == 1) {
	            auditFail(dyContentId, "5"); // 机器审核不通过
	            ILOG.info("content machine audit text of video not pass, id: {}, content: {}, image: {}, video: {}", dyContentId, contentText, "", videoUrl);
	
	        } else if(ret == 2){
	            auditFail(dyContentId, "4"); // 机器审核不通过
	            ILOG.info("content machine audit text of video fail, id: {}, content: {}, image: {}, video: {}",dyContentId, contentText, "", videoUrl);
	        }
	        else{
	        	auditFail(dyContentId, "F"); // 机器审核不通过
	            ILOG.info("content machine audit text of video fail, id: {}, content: {}, image: {}, video: {},ret :{}", dyContentId, contentText, "", videoUrl,ret);
	        }
    	}catch(Exception e){
    		ILOG.error("audi Error",e);
    	}
        return ret;
    }
	
	
	
	public void auditPass(String dyContentID) {
        try {
//        	SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd hh:mm");
//        	String s = sdf.format(new Date());
//        	
//
//            String sql = String.format("update dy_content_unreviewed set is_approved='3', audi_date='%s' where dy_content_id=%s ", s,dyContentID);
//            DatabaseHelper.getInstance().updateSql(sql);
//
//            ContentUnreviewedCache.getInstance().deleteCache(String.valueOf(dyContentID));
//            CacheThread.getInstance().updateContentCache(String.valueOf(dyContentID));
        	  Map<String, Object> map = new HashMap<String, Object>();
              map.put("isApproved", 3);
              map.put("dyContentId", dyContentID);
         	  contentUnreviewedMapper.updateContentUnrevieweByStatus(map);
        } catch (Exception e) {
            ILOG.error("content audit success but Exception  pass error, contentId: {}", dyContentID, e);
        }
    }
	
	 //新加接口，如果是文本，则直接放过
    public void auditPassOnline(String dyContentID) {
        try {
            //调用HTTP 通知
        	Map<String, Object> params =new HashMap<String, Object>();
    		params.put("dyID", 3991234);
    		params.put("type", 4);
    		params.put("operator", 1);
    		List<Integer> dyDataID =new ArrayList<Integer>();
    		dyDataID.add(Integer.parseInt(dyContentID));
    		params.put("dyDataID", dyDataID);
    		params.put("token", token);
    		params.put("deviceID",String.valueOf(System.currentTimeMillis()));
        	httpAPIService.doPostJson(httpUrl, JSON.toJSONString(params));
        } catch (Exception e) {
            ILOG.error("content audit success but Exception  pass error, contentId: {}", dyContentID, e);
        }
    } 
    
 
	
    public void auditFail(String dyContentID, String approved) {
        try {
             Map<String, Object> map = new HashMap<String, Object>();
             map.put("isApproved", approved);
             map.put("dyContentId", dyContentID);
        	contentUnreviewedMapper.updateContentUnrevieweByStatus(map);
//        	String v = "update dy_content_unreviewed set is_approved='%s' where dy_content_id=%s ";
//            String sql = String.format("update dy_content_unreviewed set is_approved='%s' where dy_content_id=%s ", approved, dyContentID);
 
//            if ("8".equals(approved)){
//            	//无效资源，直接删除
//            	ContentUnreviewedCache.getInstance().deleteCache(String.valueOf(dyContentID));
//            }

        } catch (Exception e) {
            ILOG.error("content audit fail write sql Exception error, contentId: {}, approved: {}", dyContentID, approved, e);
        }
    }
	
	
	
	
	
	
	
	
	
	
	
	
	
	
}
